/**
 * @Method toFormValues
 * @Description TODO
 * @Date 2021/1/21 16:34
 * @Created by HePing
 */
export default {
  parseField(orgField) {
    const list = []
    const parse = (orgField) => {
      const o = { orgField, rule: null, index: null };
      [/\[\.\]/g, /\./g, /\[\d\]/g].forEach(reg => {
        if (!reg.test(orgField)) return
        if (!o.index || reg.lastIndex < o.index) {
          o.rule = reg
          o.index = reg.lastIndex
        }
      })
      const cur = orgField.substr(0, o.index)
      o.field = cur.replace(o.rule, '')
      o.nextField = orgField.substr(o.index, orgField.length)
      if (o.rule) {
        o.reference = String(cur.match(o.rule)[0]).replace(/\[|\]/g, '')
      }
      list.push(o)
      if (o.rule && o.nextField) {
        parse(o.nextField)
      }
    }
    parse(orgField)
    return list
  },
  getFormValue(fieldPath, source) {
    if (!fieldPath || !source) return
    const fieldList = this.parseField(fieldPath)
    if (!fieldList) return
    let org = source
    fieldList.forEach(({ field, orgField, reference }) => {
      org = org[field || orgField]
      if (!isNaN(reference) && org) {
        org = org[reference]
      }
    })
    return org
  },
  setFormValue({ fieldPath, value, source }) {
    if (!fieldPath || value === undefined || value === null || !source) return
    const fieldList = this.parseField(fieldPath)
    if (!fieldList) return
    let org = source
    const list = fieldList.map(o => {
      const { field, orgField, reference } = o
      if (!field) {
        org[orgField] = value
        return org
      }
      org = org[field]
      if (!isNaN(reference)) {
        if (!org) {
          org = []
        }
        if (!org[reference]) {
          org[reference] = {}
        }
        org = org[reference]
      }
      return org
    })
    return list[0]
  }
}
